'use strict';
const db = uniCloud.database()
const usersCollection = db.collection('users')

exports.main = async (event, context) => {
	const { userId, userInfo } = event
	
	try {
		if (!userId) {
			return {
				code: -1,
				msg: '用户ID不能为空'
			}
		}
		
		// 检查用户是否存在
		const user = await usersCollection.doc(userId).get()
		if (!user.data || user.data.length === 0) {
			return {
				code: -1,
				msg: '用户不存在'
			}
		}
		
		// 如果更新用户名，检查是否与其他用户重复
		if (userInfo.username) {
			const usernameCheck = await usersCollection.where({
				username: userInfo.username,
				_id: db.command.neq(userId)
			}).count()
			
			if (usernameCheck.total > 0) {
				return {
					code: -1,
					msg: '用户名已存在'
				}
			}
		}
		
		// 如果更新手机号，检查是否与其他用户重复
		if (userInfo.mobile) {
			const mobileCheck = await usersCollection.where({
				mobile: userInfo.mobile,
				_id: db.command.neq(userId)
			}).count()
			
			if (mobileCheck.total > 0) {
				return {
					code: -1,
					msg: '手机号已存在'
				}
			}
		}
		
		// 更新用户信息
		//移除_id
		delete userInfo._id
		const updateData = {
			...userInfo,
			updateTime: Date.now()
		}
		
		await usersCollection.doc(userId).update(updateData)
		
		return {
			code: 0,
			msg: '更新成功'
		}
	} catch (e) {
		console.error('更新用户失败', e)
		return {
			code: -1,
			msg: '更新失败',
			error: e
		}
	}
} 